package com.tiancheng.trade.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancheng.trade.commom.core.data.PageInfo;
import com.tiancheng.trade.commom.core.exception.BusinessException;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.bo.InvoiceOrderBO;
import com.tiancheng.trade.order.bo.InvoiceResultBO;
import com.tiancheng.trade.order.bo.cmq.InvoiceResultMsgBO;
import com.tiancheng.trade.order.enums.InvoiceOrderStatusEnum;
import com.tiancheng.trade.order.enums.InvoiceStatusEnum;
import com.tiancheng.trade.order.enums.OrderSourceEnum;
import com.tiancheng.trade.order.feign.InvoiceSystemService;
import com.tiancheng.trade.order.feign.UserCenterService;
import com.tiancheng.trade.order.feign.dto.InvoiceDTO;
import com.tiancheng.trade.order.feign.dto.UserInvoiceTitleInfoDTO;
import com.tiancheng.trade.order.mapper.InvoiceOrderMapper;
import com.tiancheng.trade.order.model.InvoiceOrder;
import com.tiancheng.trade.order.service.InvoiceOrderService;
import com.tiancheng.trade.order.util.EnumUtil;
import com.tiancheng.trade.order.util.ObjectConvertUtil;
import com.tiancheng.trade.order.mq.MessageProducer;
import com.tiancheng.trade.order.vo.app.InvoiceMakeVO;
import com.tiancheng.trade.order.vo.app.InvoiceOrderQueryVO;
import com.tiancheng.trade.order.vo.app.res.InvoiceMakeResVO;
import com.tiancheng.trade.order.vo.app.res.InvoiceOrderDetailResVO;
import com.tiancheng.trade.order.vo.app.res.InvoiceOrderQueryResVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 开票订单Service接口实现
 *
 * @author kellen
 * @date 2024/6/25
 */
@Slf4j
@Service
public class InvoiceOrderServiceImpl implements InvoiceOrderService {

    @Resource
    private InvoiceOrderMapper invoiceOrderMapper;
    @Resource
    private InvoiceSystemService invoiceSystemService;
    @Resource
    private UserCenterService userCenterService;
    @Resource
    private MessageProducer messageProducer;

    @Override
    public void syncInvoiceItems(InvoiceOrderBO invoiceOrderBO) {
        try {
            if(InvoiceOrderStatusEnum.paid.getCode().equals(invoiceOrderBO.getOrderStatus())) {
                this.paid(invoiceOrderBO);
            } else if (InvoiceOrderStatusEnum.update.getCode().equals(invoiceOrderBO.getOrderStatus())) {
                this.update(invoiceOrderBO);
            } else if (InvoiceOrderStatusEnum.refund.getCode().equals(invoiceOrderBO.getOrderStatus())) {
                this.refund(invoiceOrderBO);
            } else if (InvoiceOrderStatusEnum.completed.getCode().equals(invoiceOrderBO.getOrderStatus())) {
                this.completed(invoiceOrderBO);
            } else {
                throw new Exception("同步的订单开票明细，未知的状态");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 已支付，保存未开票的订单明细
     * @param invoiceOrderBO
     */
    private void paid(InvoiceOrderBO invoiceOrderBO) {
        InvoiceOrder invoiceOrder = ObjectConvertUtil.convert(invoiceOrderBO, InvoiceOrder.class).get();

        // 如果可开票金额为0，状态置为不可开票
        invoiceOrder.setInvoiceStatus(invoiceOrderBO.getInvoiceAmount().intValue() == 0 ?
                InvoiceStatusEnum.cannot.getCode() : InvoiceStatusEnum.init.getCode());
        invoiceOrder.setCreatedDt(LocalDateTime.now());

        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", invoiceOrderBO.getUid());
        conditions.eq("order_id", invoiceOrderBO.getOrderId());
        InvoiceOrder existInvoiceOrder = invoiceOrderMapper.selectOne(conditions);

        if(existInvoiceOrder != null) {
            invoiceOrderMapper.update(invoiceOrder, conditions);
        } else {
            invoiceOrderMapper.insert(invoiceOrder);
        }
    }

    /**
     * 更新可开票信息
     * @param invoiceOrderBO
     */
    private void update(InvoiceOrderBO invoiceOrderBO) {
        InvoiceOrder invoiceOrder = ObjectConvertUtil.convert(invoiceOrderBO, InvoiceOrder.class).get();

        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", invoiceOrderBO.getUid());
        conditions.eq("order_id", invoiceOrderBO.getOrderId());
        InvoiceOrder existInvoiceOrder = invoiceOrderMapper.selectOne(conditions);

        if(existInvoiceOrder != null) {
            invoiceOrder.setLastUpdDt(LocalDateTime.now());
            invoiceOrder.setOrderStatus(existInvoiceOrder.getOrderStatus());    // update更新状态不入库，还维持订单原状态
            invoiceOrderMapper.update(invoiceOrder, conditions);

            // 如果是待开票状态，将信息同步更新到电票系统
            if(InvoiceStatusEnum.wait.getCode().equals(existInvoiceOrder.getInvoiceStatus())) {
                InvoiceDTO invoiceDTO = new InvoiceDTO();
                invoiceDTO.setOrderId(invoiceOrder.getOrderId());
                invoiceDTO.setAmount(invoiceOrder.getInvoiceAmount());
                invoiceDTO.setInvoiceSn(existInvoiceOrder.getInvoiceSn());
                invoiceDTO.setInvoiceTypeCode(invoiceOrder.getInvoiceTypeCode());

                InvoiceDTO.OrderInfo orderInfo = new InvoiceDTO.OrderInfo();
                orderInfo.setOrderName(!StringUtils.isEmpty(invoiceOrder.getOrderName()) ? invoiceOrder.getOrderName() : existInvoiceOrder.getOrderName());
                orderInfo.setGoodsType(invoiceOrder.getInvoiceNum() != null ? invoiceOrder.getInvoiceNum() : existInvoiceOrder.getInvoiceNum());
                invoiceDTO.setOrderInfo(JsonUtil.toJsonString(orderInfo));

                invoiceDTO.setItems(this.getSubmitItems(invoiceOrder.getItems()));
                invoiceSystemService.update(invoiceDTO);
            }
        } else {
            // 如果可开票金额为0，状态置为不可开票
            invoiceOrder.setInvoiceStatus(invoiceOrderBO.getInvoiceAmount().intValue() == 0 ?
                    InvoiceStatusEnum.cannot.getCode() : InvoiceStatusEnum.init.getCode());
            invoiceOrder.setCreatedDt(LocalDateTime.now());
            invoiceOrderMapper.insert(invoiceOrder);
        }
    }

    /**
     * 已退款，更新订单明细，如果已经开票，就发起冲红
     * @param invoiceOrderBO
     * @throws BusinessException
     */
    private void refund(InvoiceOrderBO invoiceOrderBO) throws BusinessException {
        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", invoiceOrderBO.getUid());
        conditions.eq("order_id", invoiceOrderBO.getOrderId());
        InvoiceOrder invoiceOrder = invoiceOrderMapper.selectOne(conditions);
        BusinessErrorInfoEnum.ORDER_INVOICE_NO_DATA.assertNotNull(invoiceOrder);

        /* ---------- 先更新本系统数据，不做事务回滚 */
        InvoiceOrder updateInvoiceOrder = new InvoiceOrder();
        // 如果退款后，可开票金额为0，此单就不可开票
        if (invoiceOrderBO.getInvoiceAmount().intValue() == 0) {
            updateInvoiceOrder.setInvoiceStatus(InvoiceStatusEnum.cannot.getCode());
        }

        updateInvoiceOrder.setRefundAmount(invoiceOrderBO.getRefundAmount());
        // 如果订单状态曾经流转到已完结，后续此状态不做变更
        if(!InvoiceOrderStatusEnum.completed.getCode().equals(invoiceOrder.getOrderStatus())) {
            updateInvoiceOrder.setOrderStatus(invoiceOrderBO.getOrderStatus());
        }
        updateInvoiceOrder.setInvoiceAmount(invoiceOrderBO.getInvoiceAmount());
        updateInvoiceOrder.setLastUpdDt(LocalDateTime.now());
        if(invoiceOrderBO.getItemsNum() != null) {
            updateInvoiceOrder.setItemsNum(invoiceOrderBO.getItemsNum());
        }
        if(!StringUtils.isEmpty(invoiceOrderBO.getItems())) {
            updateInvoiceOrder.setItems(invoiceOrderBO.getItems());
        }
        invoiceOrderMapper.update(updateInvoiceOrder, conditions);

        // 调用电子发票系统
        if(InvoiceStatusEnum.wait.getCode().equals(invoiceOrder.getInvoiceStatus())) {
            // 如果是待开票状态，通知电票系统更新数据
            InvoiceDTO invoiceDTO = new InvoiceDTO();
            invoiceDTO.setOrderId(invoiceOrderBO.getOrderId());
            invoiceDTO.setAmount(invoiceOrderBO.getInvoiceAmount());
            invoiceDTO.setInvoiceSn(invoiceOrder.getInvoiceSn());

            if(invoiceOrderBO.getItemsNum() != null) {
                invoiceDTO.setOrderInfo(JsonUtil.toJsonString(new InvoiceDTO.OrderInfo(invoiceOrder.getOrderName(), invoiceOrderBO.getItemsNum())));
            }
            invoiceDTO.setItems(this.getSubmitItems(invoiceOrderBO.getItems()));
            invoiceSystemService.update(invoiceDTO);
        } else if (InvoiceStatusEnum.completed.getCode().equals(invoiceOrder.getInvoiceStatus())) {
            // 如果是已开票状态，就冲红
            boolean redResult = invoiceSystemService.red(invoiceOrder.getOrderSource(), invoiceOrder.getInvoiceSn(), invoiceOrder.getOrderId());
            BusinessErrorInfoEnum.ORDER_INVOICE_REFUND_RED_FAIL.assertIsTrue(redResult, invoiceOrder.getOrderId());
        }
    }

    /**
     * 完结订单，更新最新的订单明细，如果处理待开票状态，直接提交开票
     * @param invoiceOrderBO
     * @throws BusinessException
     */
    private void completed(InvoiceOrderBO invoiceOrderBO) throws BusinessException {
        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", invoiceOrderBO.getUid());
        conditions.eq("order_id", invoiceOrderBO.getOrderId());
        InvoiceOrder invoiceOrder = invoiceOrderMapper.selectOne(conditions);

        // 如果为空就保存
        if(invoiceOrder == null) {
            invoiceOrder = ObjectConvertUtil.convert(invoiceOrderBO, InvoiceOrder.class).get();
            // 如果可开票金额为0，状态置为不可开票
            invoiceOrder.setInvoiceStatus(invoiceOrderBO.getInvoiceAmount().intValue() == 0 ?
                    InvoiceStatusEnum.cannot.getCode() : InvoiceStatusEnum.init.getCode());
            invoiceOrder.setCreatedDt(LocalDateTime.now());
            invoiceOrderMapper.insert(invoiceOrder);
            return;
        }

        /* ---------- 先更新本系统数据，不做事务回滚 */
        InvoiceOrder updateInvoiceOrder = new InvoiceOrder();
        updateInvoiceOrder.setOrderStatus(invoiceOrderBO.getOrderStatus());
        updateInvoiceOrder.setInvoiceAmount(invoiceOrderBO.getInvoiceAmount());
        if (invoiceOrderBO.getInvoiceNum() != null) {
            updateInvoiceOrder.setInvoiceNum(invoiceOrderBO.getInvoiceNum());
        }
        if (invoiceOrderBO.getInvoiceAmount().intValue() == 0) {
            updateInvoiceOrder.setInvoiceStatus(InvoiceStatusEnum.cannot.getCode());
        }
        updateInvoiceOrder.setItemsNum(invoiceOrderBO.getItemsNum());
        updateInvoiceOrder.setItems(invoiceOrderBO.getItems());
        updateInvoiceOrder.setLastUpdDt(LocalDateTime.now());
        invoiceOrderMapper.update(updateInvoiceOrder, conditions);

        // 取更新前的开票状态
        String invoiceStatus = invoiceOrder.getInvoiceStatus();
        // 如果是待开票状态，就提交开票
        if(InvoiceStatusEnum.wait.getCode().equals(invoiceStatus)) {
            InvoiceDTO invoiceDTO = new InvoiceDTO();
            invoiceDTO.setOrderId(invoiceOrder.getOrderId());
            invoiceDTO.setAmount(invoiceOrderBO.getInvoiceAmount());
            invoiceDTO.setInvoiceSn(invoiceOrder.getInvoiceSn());
            invoiceDTO.setInvoiceTypeCode(invoiceOrder.getInvoiceTypeCode());
            if(invoiceOrderBO.getItemsNum() != null) {
                invoiceDTO.setOrderInfo(JsonUtil.toJsonString(new InvoiceDTO.OrderInfo(invoiceOrder.getOrderName(), invoiceOrderBO.getItemsNum())));
            }

            invoiceDTO.setItems(this.getSubmitItems(invoiceOrderBO.getItems()));
            invoiceSystemService.submitBlue(invoiceDTO);
        }
    }

    /**
     * 组织提交开票的明细
     * @param itemStr
     * @return
     */
    private List<InvoiceDTO.Item> getSubmitItems(String itemStr) {
        List<InvoiceDTO.Item> submitItems = new ArrayList<>();
        List<Map<String, Object>> items = JsonUtil.fromJson(itemStr, List.class);
        items.forEach(item -> {
            InvoiceDTO.Item submitItem = new InvoiceDTO.Item();
            submitItem.setCode(String.valueOf(item.get("code")));
            submitItem.setName(String.valueOf(item.get("name")));
            submitItem.setAmount(Integer.valueOf(String.valueOf(item.get("amount"))));
            submitItem.setBusinessNum(Integer.valueOf(String.valueOf(item.get("num"))));
            if(item.containsKey("tax_code")) {
                submitItem.setTaxCode(String.valueOf(item.get("tax_code")));
            }
            if(item.containsKey("tax_rate")) {
                submitItem.setTaxRate(Integer.valueOf(String.valueOf(item.get("tax_rate"))));
            }
            if(item.containsKey("free_tax_rate")) {
                submitItem.setFreeTaxRate(Integer.valueOf(String.valueOf(item.get("free_tax_rate"))));
            }
            if(item.containsKey("price")) {
                submitItem.setBusinessUnitPrice(Integer.valueOf(String.valueOf(item.get("price"))));
            }
            if(item.containsKey("model")) {
                submitItem.setBusinessModels(String.valueOf(item.get("model")));
            }
            if(item.containsKey("unit")) {
                submitItem.setBusinessUnit(String.valueOf(item.get("unit")));
            }
            submitItems.add(submitItem);
        });
        return submitItems;
    }

    @Override
    public void syncInvoiceItemsAndMake(InvoiceOrderBO invoiceOrderBO) {
        InvoiceOrder invoiceOrder = ObjectConvertUtil.convert(invoiceOrderBO, InvoiceOrder.class).get();

        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", invoiceOrderBO.getUid());
        conditions.eq("order_id", invoiceOrderBO.getOrderId());
        InvoiceOrder existInvoiceOrder = invoiceOrderMapper.selectOne(conditions);
        // 判断是否重复开票
        BusinessErrorInfoEnum.ORDER_INVOICE_DUP.assertIsTrue(existInvoiceOrder == null ||
                !InvoiceStatusEnum.completed.getCode().equals(existInvoiceOrder.getInvoiceStatus()));

        if(existInvoiceOrder != null) {
            if(invoiceOrderBO.getInvoiceAmount().intValue() == 0) {
                invoiceOrder.setInvoiceStatus(InvoiceStatusEnum.cannot.getCode());
            } else {
                invoiceOrder.setInvoiceStatus(existInvoiceOrder.getInvoiceStatus());
            }
            invoiceOrderMapper.update(invoiceOrder, conditions);
        } else {
            // 如果可开票金额为0，状态置为不可开票
            invoiceOrder.setInvoiceStatus(invoiceOrderBO.getInvoiceAmount().intValue() == 0 ?
                    InvoiceStatusEnum.cannot.getCode() : InvoiceStatusEnum.wait.getCode());
            invoiceOrder.setCreatedDt(LocalDateTime.now());
            invoiceOrderMapper.insert(invoiceOrder);
        }

        // 如果是新增或者是待开票状态，就直接提交开票
        if(InvoiceStatusEnum.init.getCode().equals(invoiceOrder.getInvoiceStatus()) ||
                InvoiceStatusEnum.wait.getCode().equals(invoiceOrder.getInvoiceStatus())) {
            // 提交电子发票系统参数
            InvoiceDTO invoiceDTO = ObjectConvertUtil.convert(invoiceOrderBO, InvoiceDTO.class).get();
            invoiceDTO.setChannel(invoiceOrder.getOrderSource());
            invoiceDTO.setUserOpenid(invoiceOrder.getUid());
            invoiceDTO.setAmount(invoiceOrder.getInvoiceAmount());
            invoiceDTO.setItems(this.getSubmitItems(invoiceOrder.getItems()));
            invoiceDTO.setOrderInfo(JsonUtil.toJsonString(new InvoiceDTO.OrderInfo(invoiceOrder.getOrderName(), invoiceOrder.getItemsNum())));
            String invoiceSn = invoiceSystemService.blue(invoiceDTO);

            InvoiceOrder updateInvoiceOrder = new InvoiceOrder();
            updateInvoiceOrder.setInvoiceSn(invoiceSn);
            invoiceOrderMapper.update(updateInvoiceOrder, conditions);
        }
    }

    @Override
    public PageInfo<InvoiceOrderQueryResVO> query(String uid, InvoiceOrderQueryVO queryVO) {
        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", uid);
        conditions.eq("invoice_status", InvoiceStatusEnum.init.getCode());
        // 89是诚选订单
        if(queryVO.getOrderSource() != null && "89".equals(queryVO.getOrderSource())) {
            conditions.eq("order_source", "89");
        } else {
            conditions.ne("order_source", "89");
        }
        conditions.orderByDesc("order_pay_time");

        PageInfo<InvoiceOrder> invoiceOrders = invoiceOrderMapper.find(conditions, queryVO.getPage(), queryVO.getSize());

        List<InvoiceOrderQueryResVO> resVOS = new ArrayList<>();
        invoiceOrders.getList().forEach(invoiceOrder -> {
            InvoiceOrderQueryResVO resVO = ObjectConvertUtil.convert(invoiceOrder, InvoiceOrderQueryResVO.class).get();
            if("89".equals(invoiceOrder.getOrderSource())) {
                resVO.setOrderSourceName("诚选");
            } else {
                resVO.setOrderSourceName(EnumUtil.getEnumByCode(OrderSourceEnum.class, invoiceOrder.getOrderSource()).desc());
            }
            resVOS.add(resVO);
        });
        return new PageInfo<>(resVOS, invoiceOrders.getPagination());
    }

    @Override
    public InvoiceMakeResVO make(String uid, InvoiceMakeVO invoiceMakeVO) throws BusinessException {
        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", uid);
        conditions.eq("order_id", invoiceMakeVO.getOrderId());
        conditions.eq("invoice_status", InvoiceStatusEnum.init.getCode());
        InvoiceOrder invoiceOrder = invoiceOrderMapper.selectOne(conditions);
        BusinessErrorInfoEnum.ORDER_INVOICE_NO_DATA.assertNotNull(invoiceOrder);

        // 提交电子发票系统参数
        InvoiceDTO invoiceDTO = ObjectConvertUtil.convert(invoiceMakeVO, InvoiceDTO.class).get();
        invoiceDTO.setChannel(invoiceOrder.getOrderSource());
        invoiceDTO.setUserOpenid(uid);
        invoiceDTO.setInvoiceTypeCode(invoiceOrder.getInvoiceTypeCode());
        invoiceDTO.setSellerTaxpayerNum(invoiceOrder.getSellerTaxpayerNum());
        invoiceDTO.setSellerTaxpayerSn(invoiceOrder.getSellerTaxpayerSn());
        invoiceDTO.setOrderId(invoiceOrder.getOrderId());
        invoiceDTO.setAmount(invoiceOrder.getInvoiceAmount());
        invoiceDTO.setItems(this.getSubmitItems(invoiceOrder.getItems()));
        invoiceDTO.setOrderInfo(JsonUtil.toJsonString(new InvoiceDTO.OrderInfo(invoiceOrder.getOrderName(), invoiceOrder.getItemsNum())));
        invoiceDTO.setTemplate(invoiceOrder.getTemplate());
        invoiceDTO.setTemplateInfo(invoiceOrder.getTemplateInfo());

        // 更新可开票订单记录
        InvoiceOrder updateInvoiceOrder = new InvoiceOrder();
        updateInvoiceOrder.setLastUpdDt(LocalDateTime.now());

        // 如果订单已完结，就直接提交开票，否则待提交状态
        if (InvoiceOrderStatusEnum.completed.getCode().equals(invoiceOrder.getOrderStatus())) {
            String invoiceSn = invoiceSystemService.blue(invoiceDTO);
            updateInvoiceOrder.setInvoiceSn(invoiceSn);
            updateInvoiceOrder.setInvoiceStatus(InvoiceStatusEnum.completed.getCode());
        } else {
            String invoiceSn = invoiceSystemService.createBlue(invoiceDTO);
            updateInvoiceOrder.setInvoiceSn(invoiceSn);
            updateInvoiceOrder.setInvoiceStatus(InvoiceStatusEnum.wait.getCode());
        }
        invoiceOrderMapper.update(updateInvoiceOrder, conditions);

        // 保存发票抬头信息到用户中心
        try {
            UserInvoiceTitleInfoDTO titleInfoDTO = ObjectConvertUtil.convert(invoiceMakeVO, UserInvoiceTitleInfoDTO.class).get();
            titleInfoDTO.setUserId(uid);
            userCenterService.saveInvoiceTitleInfo(titleInfoDTO);
        } catch (Exception e) {
            log.error("开具发票保存个人信息出错:{}", e.getMessage(), e);
        }

        return new InvoiceMakeResVO(invoiceOrder.getOrderId(), updateInvoiceOrder.getInvoiceSn(), updateInvoiceOrder.getInvoiceStatus());
    }

    @Override
    public InvoiceOrderDetailResVO detail(String uid, String orderId) {
        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", uid);
        conditions.eq("order_id", orderId);
        InvoiceOrder invoiceOrder = invoiceOrderMapper.selectOne(conditions);
        return ObjectConvertUtil.convert(invoiceOrder, InvoiceOrderDetailResVO.class).get();
    }

    @Override
    public void invoiceResult(InvoiceResultBO invoiceResultBO) {
        try {
            QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
            conditions.eq("order_id", invoiceResultBO.getOrderId());
            InvoiceOrder invoiceOrder = invoiceOrderMapper.selectOne(conditions);
            BusinessErrorInfoEnum.ORDER_INVOICE_NO_DATA.assertNotNull(invoiceOrder);

            InvoiceOrder updateInvoiceOrder = new InvoiceOrder();
            updateInvoiceOrder.setInvoiceSn(invoiceResultBO.getInvoiceSn());
            if(invoiceResultBO.getTicketType() == 1 && invoiceResultBO.getTicketStatus() == 2) {
                // 开具蓝票成功时
                updateInvoiceOrder.setInvoiceStatus(InvoiceStatusEnum.completed.getCode());
            } else if (invoiceResultBO.getTicketType() == 2 && invoiceResultBO.getTicketStatus() == 2 &&
                    !InvoiceStatusEnum.cannot.getCode().equals(invoiceOrder.getInvoiceStatus())) {
                // 冲红成功时，并且订单开票状态不是cannot
                updateInvoiceOrder.setInvoiceStatus(InvoiceStatusEnum.init.getCode());
            }
            invoiceOrderMapper.update(updateInvoiceOrder, conditions);

            // 开票、冲红结果通知业务侧
            InvoiceResultMsgBO msgBO = ObjectConvertUtil.convert(invoiceResultBO, InvoiceResultMsgBO.class).get();
        } catch (Exception e) {
            log.error("开票结果回调失败: {}", e.getMessage(), e);
        }
    }

    @Override
    public void reset(String uid, InvoiceMakeVO invoiceMakeVO) throws BusinessException {
        QueryWrapper<InvoiceOrder> conditions = new QueryWrapper<>();
        conditions.eq("uid", uid);
        conditions.eq("order_id", invoiceMakeVO.getOrderId());
        InvoiceOrder invoiceOrder = invoiceOrderMapper.selectOne(conditions);
        BusinessErrorInfoEnum.ORDER_INVOICE_NO_DATA.assertNotNull(invoiceOrder);

        // 保存发票抬头信息到用户中心
        try {
            UserInvoiceTitleInfoDTO titleInfoDTO = ObjectConvertUtil.convert(invoiceMakeVO, UserInvoiceTitleInfoDTO.class).get();
            titleInfoDTO.setUserId(uid);
            userCenterService.saveInvoiceTitleInfo(titleInfoDTO);
        } catch (Exception e) {
            log.error("重新开具发票保存个人信息出错:{}", e.getMessage(), e);
        }

        InvoiceDTO invoiceDTO = ObjectConvertUtil.convert(invoiceMakeVO, InvoiceDTO.class).get();
        invoiceDTO.setUserOpenid(uid);
        invoiceDTO.setInvoiceSn(invoiceOrder.getInvoiceSn());
        invoiceDTO.setChannel(invoiceOrder.getOrderSource());

        try {
            invoiceSystemService.reset(invoiceDTO);
        } catch (Exception e) {
            throw new BusinessException(BusinessErrorInfoEnum.ORDER_INVOICE_RESET_FAIL, null, e.getMessage(), e);
        }
    }
}
